<template>
  <div class="app-container">
    <el-card>
      <CategorySelector
        @changeCategory="changeCategory"
        :isShowList="isShowList"
      />
    </el-card>

    <el-card style="margin-top:20px">
      <div v-show="isShowList">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="showAddDiv"
          :disabled="!category3Id"
          >添加属性</el-button
        >
        <el-table :data="attrList" style="width: 100%">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80"
          ></el-table-column>
          <el-table-column prop="attrName" label="属性名称"></el-table-column>
          <el-table-column label="属性值列表">
            <template slot-scope="{ row, $index }">
              <el-tag
                type="success"
                v-for="(attrValue, index) in row.attrValueList"
                :key="attrValue.id"
                >{{ attrValue.valueName }}</el-tag
              >
            </template>
          </el-table-column>

          <el-table-column label="操作" width="150" align="center">
            <template slot-scope="{ row, $index }">
              <HintButton
                type="warning"
                icon="el-icon-edit"
                size="mini"
                title="修改"
                @click="showUpdateDiv(row)"
              />

              <el-popconfirm
                :title="`确认删除${row.attrName}吗？`"
                @onConfirm="deleteAttr(row)"
              >
                <HintButton
                  slot="reference"
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  title="删除"
                />
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-show="!isShowList">
        <el-form :model="attrForm" :inline="true">
          <el-form-item label="属性名">
            <el-input
              v-model="attrForm.attrName"
              placeholder="请输入属性名称"
            ></el-input>
          </el-form-item>
        </el-form>

        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!attrForm.attrName"
          @click="addAttrValue"
          >添加属性值</el-button
        >
        <el-button @click="isShowList = true">取消</el-button>
        <p />
        <el-table :data="attrForm.attrValueList" border style="width:100%">
          <el-table-column
            label="序号"
            type="index"
            width="80"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template slot-scope="{ row, $index }">
              <el-input
                :ref="$index"
                v-model="row.valueName"
                placeholder="请输入属性值名称"
                v-if="row.isEdit"
                @blur="toLook(row)"
                @keyup.enter.native="toLook(row)"
                size="mini"
              />
              <span
                v-else
                @click="toEdit(row, $index)"
                style=" display:block;width:100%;height:100%; "
                >{{ row.valueName }}</span
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" align="center">
            <template slot-scope="{ row, $index }">
              <el-popconfirm
                :title="`确认删除${row.valueName}吗？`"
                @onConfirm="attrForm.attrValueList.splice($index, 1)"
              >
                <HintButton
                  slot="reference"
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  title="删除属性"
                ></HintButton>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <p />
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="save"
          :disabled="attrForm.attrValueList.length === 0"
          >保存</el-button
        >
        <el-button @click="isShowList = true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { cloneDeep } from 'lodash'
export default {
  name: 'Attr',
  data() {
    return {
      category1Id: '',
      category2Id: '',
      category3Id: '',
      attrList: [],
      isShowList: true,
      attrForm: {
        attrName: '',
        attrValueList: [],
        categoryId: 0,
        categoryLevel: 3
      }
    }
  },
  methods: {
    changeCategory({ categoryId, level }) {
      if (level === 1) {
        this.category1Id = categoryId

        this.category2Id = ''
        this.category3Id = ''
        this.attrList = []
      } else if (level === 2) {
        this.category2Id = categoryId
        // 二级选中以后，三级应该清空
        this.category3Id = ''
        this.attrList = []
      } else {
        this.category3Id = categoryId

        // 只有在三级分类获取到以后，才能进行数据的请求操作
        this.getAttrList()
      }
    },
    // 获取属性列表
    async getAttrList() {
      const { category1Id, category2Id, category3Id } = this
      const result = await this.$API.attr.getList(
        category1Id,
        category2Id,
        category3Id
      )

      if (result.code === 200) {
        this.attrList = result.data
      }
    },
    // 确认显示添加的div图层
    showAddDiv() {
      this.isShowList = false

      this.attrForm = {
        attrName: '',
        attrValueList: [],
        categoryId: this.category3Id,
        categoryLevel: 3
      }
    },
    // 添加属性值
    addAttrValue() {
      this.attrForm.attrValueList.push({
        attrId: this.attrForm.id,
        valueName: '',
        isEdit: true
      })

      this.$nextTick(() => {
        this.$refs[this.attrForm.attrValueList.length - 1].focus()
      })
    },
    // 修改属性
    showUpdateDiv(row) {
      this.isShowList = false

      this.attrForm = cloneDeep(row) // 深拷贝

      this.attrForm.attrValueList.forEach(item => {
        this.$set(item, 'isEdit', false)
      })
    },
    // 切换到查看模式
    toLook(row) {
      let valueName = row.valueName
      if (!valueName.trim()) {
        this.$message('输入的属性名称不能为空')
        row.valueName = ''
        return // 中断
      }

      // 2.输入的数据不能和已存在的数据进行重复，需要进行循环判断，判断数组当中是否已经存在，可以利用数组操作的some函数
      let isRepeat = this.attrForm.attrValueList.some(item => {
        if (item !== row) {
          // 除去自身以后，有一个达到return的条件，那么就需要返回true
          return item.valueName === valueName
        }
      })

      if (isRepeat) {
        this.$message('输入的属性名称不能重复')
        row.valueName = '' // 因为重复了，所以数据要清空
        return // 中断
      }

      row.isEdit = false
    },
    // 切换到编辑模式
    toEdit(row, index) {
      row.isEdit = true

      this.$nextTick(() => {
        this.$refs[index].focus()
      })
    },

    // 保存数据
    async save() {
      // 1.获取到需要保存的表单数据
      let attr = this.attrForm

      attr.attrValueList = attr.attrValueList.filter(item => {
        if (item.valueName !== '') {
          delete item.isEdit
          return true
        }
      })

      if (attr.attrValueList.length === 0) return

      // 3.发送请求
      try {
        // 4.成功
        await this.$API.attr.addOrUpdate(attr)
        // 1.提示
        this.$message.success('保存成功')
        // 2.返回列表
        this.isShowList = true
        // 3.重新获取列表的数据
        this.getAttrList()
      } catch (error) {
        // 5.失败
        this.$message.error('保存失败')
      }
    },

    // 删除属性
    async deleteAttr(row) {
      try {
        await this.$API.attr.delete(row.id)
        this.$message.success('删除成功')
        this.getAttrList()
      } catch (error) {
        this.$message.error('删除失败')
      }
    }
  }
}
</script>

<style></style>
